//
//  String+Extension.swift
//  TDDStudySwift
//
//  Created by baidu on 6/28/16.
//  Copyright © 2016 caoyuan. All rights reserved.
//

import Foundation

extension String {
    
    subscript (r: Range<Int>) -> String {
        get {
            let startIndex = self.characters.index(self.startIndex, offsetBy: r.lowerBound)
            let endIndex = self.characters.index(self.startIndex, offsetBy: r.upperBound)
            return self[startIndex..<endIndex]
        }
    }
    
    subscript (s: String) -> Int {
        get {
            if let range =  self.range(of: s) {
                return self.characters.distance(from: self.startIndex, to: range.lowerBound)
            } else {
                return -1
            }
        }
    }
    
    subscript (index: Int) -> String {
        get {
            return self[index..<index + 1]
        }
    }
    
    func pySplit(str:Character) -> [String] {
        let stra = self.characters.split(separator: str).map { (String($0)) }
        return stra
    }
    
    func pyReplace(str:String, withStr:String) -> String {
        return self.replacingOccurrences(of: str, with: withStr)
    }
    
    
    
// reverse a string...
    func pyReverse() -> String {
        var b = [Character](self.characters)
        var start = 0
        var end = b.count - 1
        while start < end {
            let tmp = b[start]
            b[start] = b[end]
            b[end] = tmp
            start += 1
            end -= 1
        }
        return String(b)
    }
}
